package cn.web.tunnelrobot.util;

import cn.web.tunnelrobot.dto.ConstructionScheduleDTO;
import cn.web.tunnelrobot.dto.RealTimeData;
import cn.web.tunnelrobot.dto.Warning;
import cn.web.tunnelrobot.pojo.Threshold;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 常量+变量
 * @author Lichuang
 * @version 1.0.0
 * 
 */
public class Constants {
	//是否内网，1内网 0外网,此处可以优化到配置文件来设置
	public static Integer is_intranet = 0;

	public final static String USER_SESSION = "userSession";
	public static Integer TerminalControl = 0;//pc、pad、机器人端正在控制
	public static Integer voiceTerminal = 0;//pc、pad端正在语音对讲
	public static List<Threshold> list = new ArrayList<>();
	//(1:温度 2:湿度 3:氧气浓度 4:光照强度 5:粉尘浓度 6:瓦斯浓度 7:电量预警)=>进行阈值判断添加警告问题
	public static List<Threshold> temperature = new ArrayList<>();//1温度
	public static List<Threshold> humidity = new ArrayList<>();//2湿度
	public static List<Threshold> oxygenConcentrations = new ArrayList<>();//3氧气浓度
//	public static List<Threshold> lightIntensity = new ArrayList<>();//光照强度
	public static List<Threshold> dustConcentration = new ArrayList<>();//4粉尘浓度
	public static List<Threshold> gasDensity = new ArrayList<>();//5瓦斯浓度
	public static List<Threshold> batteryWarning = new ArrayList<>();//6电量预警
	public static List<Threshold> spareBatteryWarning = new ArrayList<>();//备用电量10
	public static Threshold settle = new Threshold();//沉降7
	public static Threshold convergence = new Threshold();//收敛8
//	public static Threshold gyroscope = new Threshold();
	public static Threshold cloudTurnAngle = new Threshold();//云转向角度9
	public static RealTimeData realTimeData = new RealTimeData();//8个实时数据

	//服务器地址(当前地址)
	//public  final static String fwqAddress = "https://tkws.tgmis.cn:8082";
	public  final static String fwqAddress = "https://tkws.tgmis.cn:10011";

	//机器人调用地址
//	public  final static String robotAddress = "http://3m47609m22.wicp.vip/robot";
//	public  final static String robotAddress = "http://jqr.liguoxian.com/robot";
//	public  final static String robotAddress = "http://192.168.0.113:8080/robot";
//	public  final static String robotAddress = "http://192.168.0.110:8080";
//	public  final static String robotAddress = "http://localhost:8091";
		//工控机花生壳映射
//	public  final static String robotAddress = "http://449z7031f9.qicp.vip:59814";
		//工控机frp映射后地址，后面服务端要用这个地址连接机器端
//	public  final static String robotAddress = "http://43.140.249.105:8091";
//	public  final static String robotAddress = "http://192.168.1.101:8091";
	//修改机器人后端地址
	public  final static String robotAddress = "http://10.168.1.100:8091";
	//  改变为公网ip后的地质
//	public  final static String robotAddress = "http://208.67.222.222:8091";


	//内外网摄像头地址获取接口
	public final static String cameraadress = robotAddress + "/DahuaCamera/adress";
	//硬件0：湿度 1：氧气 2：温度 3：湿度 4:可燃气体 5:PM2.5 6:电量(二期)
	public final static  String obstacleAddress=robotAddress+"/SensorData/LiveOBSTACLEData";
	public final static String hardwareAddress = robotAddress + "/SensorData/LiveHOTData";
	//硬件 获取底盘api（/log）信息取电池（二期两个电池分开）
	public final static String hardwareAddress2 = robotAddress + "/System/info";
	//图片抓拍请求路径
	public final static String captureImg =  robotAddress + "/Vidicon/ImgUrl";
	public final static String captureImge =  robotAddress + "/DahuaCamera/capture";//(二期)
	//视频抓拍请求路径(2小时有效期)
	//public final static String captureVideo =  robotAddress + "/Vidicon/ImgUrl";
	//车体控制请求路径(二期)
	public final static String carBodyControl =  robotAddress + "/System/put_speed";
	//车前后灯控制(二期)
	public final static String carBodyLight =  robotAddress + "/Lamp/Lights";//
    //报警灯实时控制(二期)
	public final static String carAlarmLight =  robotAddress + "/Lamp/AlarmLights";//
	//转向灯实时控制(二期)
	public final static String carTurnLight =  robotAddress + "/Lamp/TurnLights";//
	//机械臂臂灯控制（二期）
	public final static String carArmLight =  robotAddress + "/Lamp/ArmLights";//
	//机器人充电状态（二期）
	public final static String  chargingsState = robotAddress+"/System/galileo_status";
	//机械臂控制请求路径
	public final static String manipulatorControl =  robotAddress + "/Live/LiveArm";
	//机械臂控制（二期）
	public final static String armControl=robotAddress+"/RobotArm/robotArmControl";
	//机械臂复位（二期）
	public final static String robotArmRest=robotAddress+"/RobotArm/robotArmRest";
	//画面路径获取路径
	public final static String monitorScreen =  robotAddress + "/Vidicon/VidiconUrl";
	//获得到的画面路径获取路径(7天有效期)
	public static List<String> getsRealMonitoringAddress = new ArrayList<>();
	public static Integer voiceControl = 0;//控制机器人
	public static Integer connection = 0;//控制机器人-开启
	public static Integer shutDown = 0;//控制机器人-关闭
	public static Integer obstacleStatus = 0;//地盘状态

	//机器人语音播报
	public final static String voiceBroadcast = robotAddress + "/Live/VoiceBroadcast";
	//机器人实时位置
	public final static String robotPosition =  robotAddress + "/SensorData/LiveRFIDData";//（二期）
	//机器人云平台转向控制-开始
	public final static String taiwanStart =  robotAddress + "/DahuaCamera/ControlPtz";
	//机器人云平台转向控制-结束
	public final static String taiwanStop =  robotAddress + "/Vidicon/PtzStop";
	//机器人车灯/报警灯实时控制
	public final static String headlights =  robotAddress + "/Live/LiveHeadlights";
	//陀螺仪角度获取
	public final static String gyroscopeAngle =  robotAddress +"/LiveData/LiveGyroscopeData";
	//激光模块云盘控制
	public final static String cloudDiskControl = robotAddress +"/Sedimentation/LiveLaserCloud";//module 模块 ID angle:角度
	//获取激光模块测量数据
	public final static String metricalData =  robotAddress +"/Sedimentation/LiveLaserData";//module 模块 IDflag: 1(初始化) 0(不初始化)
	//激光模块复位
	public final static String laserReset =  robotAddress +"/Sedimentation/LiveLaserReset";//module: 模块 ID(硬件程序复位)
	//遇到障碍物(该功能在robotAddress端并不存在代码编写)（二期）
	public final static String obstacle =  robotAddress+"/SensorData/LiveOBSTACLEData";//遇到障碍物
	//语音对讲
	public final static String voiceIntercom =  robotAddress+"/Live/voiceIntercom";//语音对讲

	//实时信息警告记录(1:温度 2:湿度 3:氧气浓度 4:光照强度 5:粉尘浓度 6:瓦斯浓度 7:电量预警)-首页
	public static List<Warning> warningList = new ArrayList<>();
	//机器人实时位置-首页
	public static Integer robotCurrentPosition = 0;
	//隧道模型 每多少米一节隧道
	public static Integer Meter = 10;
	//机器人公网IP地址(判断是否是机器人)
	public static String robotPublicAddress = "117.157.105.216";
	//判断机器人是否在行走，实时数据获取问题(车停时调用温湿度    车行走时调用避障、定位、陀螺仪) 0停止 1行走
	//public static Integer robotWalk = 0;
	public static String goCharge=robotAddress+"/Navigation/go_charge";//开启自动充电
	public static String stopCharge=robotAddress+"/Navigation/stop_charge";//关闭自动充电
	public static String start=robotAddress+"/Navigation/start";//开启导航（二期）
	public static String stop=robotAddress+"/Navigation/stop_charge";//关闭导航（二期）
	public static String startScheduleMode=robotAddress+"/Navigation/start_schedule_mode";//启动调度导航（二期）
	public static String stopScheduleMode=robotAddress+"/Navigation/stop_schedule_mode";//关闭调度导航（二期）

	public static String startNavTask=robotAddress+"/Navigation/start_nav_task";//开启导航任务（二期）
	public static String stopNavTask=robotAddress+"/Navigation/stop_nav_task";//关闭导航任务（二期）
	public static String navMap=robotAddress+"/Navigation/current_path";//获取导航地图（二期）
	public static String log=robotAddress+"/System/log";//获取日志


	/** 无参数的get请求
	 *  @param url
	 *  接口地址
	 */
	public final static String doGet(String url) {
		String responseMsg = "";
		HttpClient httpClient = new HttpClient();
		GetMethod getMethod = new GetMethod(url);
		getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
		try {
			httpClient.executeMethod(getMethod);
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			InputStream in = getMethod.getResponseBodyAsStream();
			int len = 0;
			byte[] buf = new byte[1024];
			while ((len = in.read(buf)) != -1) {
				out.write(buf, 0, len);
			}
			responseMsg = out.toString("UTF-8");
		} catch (HttpException e) {
//			e.printStackTrace();
		} catch (IOException e) {
//			e.printStackTrace();
		} finally {
			//释放连接
			getMethod.releaseConnection();
		}
		return responseMsg;
	}
	/**
	 * PUT请求
	 */
	public final static String doPut(String url) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPut httpPut = new HttpPut(url);
		RequestConfig config = RequestConfig.custom().setConnectTimeout(35000) //连接超时时间
				.setConnectionRequestTimeout(35000)        //取得连接最长时间
				.setSocketTimeout(60000)                //数据传输超时时间
				.build();
		httpPut.setConfig(config);						//设置配置信息
		httpPut.setHeader("Content-type", "application/json");
		httpPut.setHeader("DataEncoding", "UTF-8");//请求头
		CloseableHttpResponse httpResponse = null;
		try {
			httpResponse = httpClient.execute(httpPut);
			HttpEntity entity = httpResponse.getEntity();
			if(entity!=null) {
				return EntityUtils.toString(entity);
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
		} finally {
			if (httpResponse != null) {
				try {
					httpResponse.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
//					e.printStackTrace();
				}
			}
			if (null != httpClient) {
				try {
					httpClient.close();
				} catch (IOException e) {
//					e.printStackTrace();
				}
			}
		}
		return null;
	}
	/**
	 * POST请求
	 */
   public final static String doPost(String url, String query) throws Exception {
        URL restURL = new URL(url);
	  //此处的urlConnection对象实际上是根据URL的请求协议(此处是http)生成的URLConnection类 的子类HttpURLConnection
        HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();
        //请求方式
        conn.setRequestMethod("POST");
        //设置是否从httpUrlConnection读入，默认情况下是true; httpUrlConnection.setDoInput(true);
        conn.setDoOutput(true);
        //allowUserInteraction 如果为 true，则在允许用户交互（例如弹出一个验证对话框）的上下文中对此 URL 进行检查。
        conn.setAllowUserInteraction(false);
        PrintStream ps = new PrintStream(conn.getOutputStream());
        ps.print(query);
        ps.close();
        BufferedReader bReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line, resultStr = "";
        while (null != (line = bReader.readLine())) {
            resultStr += line;
        }
        bReader.close();
        return resultStr;
    }
	/**
	 * 向指定URL发送GET方法的请求
	 *
	 * @param url
	 *   发送请求的URL
	 *   请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return URL 所代表远程资源的响应结果
	 */
	public static String sendGet(String url) {
		String result = "";
		BufferedReader in = null;
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 建立实际的连接
			connection.connect();
			// 获取所有响应头字段
			Map<String, List<String>> map = connection.getHeaderFields();
			// 遍历所有的响应头字段
			for (String key : map.keySet()) {
//				System.out.println(key + "--->" + map.get(key));
			}
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送GET请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}
	public static String doGet1(String httpurl) {
		HttpURLConnection connection = null;
		InputStream is = null;
		BufferedReader br = null;
		String result = null; // 返回结果字符串
		try {
			// 创建远程url连接对象
			URL url = new URL(httpurl);
			// 通过远程url连接对象打开一个连接，强转成httpURLConnection类
			connection = (HttpURLConnection) url.openConnection();
			// 设置连接方式：get
			connection.setRequestMethod("GET");
			// 设置连接主机服务器的超时时间：15000毫秒
			connection.setConnectTimeout(15000);
			// 设置读取远程返回的数据时间：60000毫秒
			connection.setReadTimeout(60000);
			// 发送请求
			connection.connect();
			// 通过connection连接，获取输入流
			if (connection.getResponseCode() == 200) {
				is = connection.getInputStream();
				// 封装输入流is，并指定字符集
				br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
				// 存放数据
				StringBuffer sbf = new StringBuffer();
				String temp = null;
				while ((temp = br.readLine()) != null) {
					sbf.append(temp);
					sbf.append("\r\n");
				}
				result = sbf.toString();
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭资源
			if (null != br) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			if (null != is) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			connection.disconnect(); // 关闭远程连接
		}

		return result;
	}

	public static void main(String[] args) {
		try {
			String value = Constants.doPost(Constants.voiceBroadcast, "content=" + "咱们走吧");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
